package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxBlCost;
import com.adk.backend.entity.LxBlDetails;
import com.adk.backend.entity.LxBlList;
import com.adk.backend.mapper.BlCostMapper;
import com.adk.backend.mapper.BlDetailsMapper;
import com.adk.backend.mapper.BlMapper;
import com.adk.backend.service.BlService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提单服务实现类
 */
@Slf4j
@Service
public class BlServiceImpl extends ServiceImpl<BlMapper, LxBlList> implements BlService {
    
    @Autowired
    private BlMapper blMapper;
    
    @Autowired
    private BlDetailsMapper blDetailsMapper;
    
    @Autowired
    private BlCostMapper blCostMapper;
    
    @Override
    public PageResult<Map<String, Object>> getBlList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        
        // 计算偏移量
        Integer offset = (pageNum - 1) * pageSize;
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        
        // 查询总数
        Long total = blMapper.countBlList(params);
        
        // 查询列表
        List<Map<String, Object>> list = blMapper.selectBlListWithInfo(params);
        
        PageResult<Map<String, Object>> result = new PageResult<>();
        result.setList(list);
        result.setTotal(total);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setTotalPages((int) Math.ceil((double) total / pageSize));
        
        return result;
    }
    
    @Override
    public LxBlList getBlById(Integer id) {
        return blMapper.selectById(id);
    }
    
    @Override
    public LxBlList getBlByBlNo(String blNo) {
        return blMapper.selectByBlNo(blNo);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxBlList createBl(LxBlList blList, Integer userId) {
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        if (blList.getAddTime() == null) {
            blList.setAddTime(currentTime);
        }
        if (userId != null && blList.getAddUid() == null) {
            blList.setAddUid(userId);
        }
        blMapper.insert(blList);
        return blList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBl(LxBlList blList, Integer userId) {
        // PHP代码中更新提单没有设置update_uid和update_time，这里也不设置（保持一致）
        return blMapper.updateById(blList) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBl(Integer id) {
        return blMapper.deleteById(id) > 0;
    }
    
    @Override
    public List<LxBlDetails> getBlDetails(Integer blId) {
        QueryWrapper<LxBlDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("bl_id", blId);
        return blDetailsMapper.selectList(wrapper);
    }
    
    @Override
    public List<LxBlCost> getBlCosts(Integer blId) {
        QueryWrapper<LxBlCost> wrapper = new QueryWrapper<>();
        wrapper.eq("bl_id", blId);
        wrapper.orderByDesc("add_time");
        return blCostMapper.selectList(wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addBlCost(LxBlCost blCost) {
        if (blCost.getAddTime() == null) {
            blCost.setAddTime((int) (System.currentTimeMillis() / 1000));
        }
        return blCostMapper.insert(blCost) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBlCost(LxBlCost blCost) {
        if (blCost.getUpdateTime() == null) {
            blCost.setUpdateTime((int) (System.currentTimeMillis() / 1000));
        }
        return blCostMapper.updateById(blCost) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBlCost(Long id) {
        return blCostMapper.deleteById(id) > 0;
    }
    
    @Override
    public List<Map<String, Object>> getBlDetailsWithOrder(Integer blId) {
        return blDetailsMapper.selectBlDetailsWithOrder(blId);
    }
    
    @Override
    public Map<String, Object> getHllFee(Integer id) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return null;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("id", bl.getId());
        result.put("blNo", bl.getBlNo());
        result.put("hllFee", bl.getHllFee());
        
        // 查询财务审核明细中的HLL费用
        // TODO: 需要创建FinanceCheckDetailsMapper来查询
        // 暂时返回提单中的HLL费用
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveHllFee(Integer id, java.math.BigDecimal hllFee, Integer userId) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return false;
        }
        
        bl.setHllFee(hllFee);
        // 与PHP逻辑一致：同时更新finance_check_details表（如果存在）
        // TODO: 实现finance_check_details表的更新逻辑
        return blMapper.updateById(bl) > 0;
    }
    
    @Override
    public Map<String, Object> getManifestFee(Integer id) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return null;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("id", bl.getId());
        result.put("blNo", bl.getBlNo());
        result.put("mainfestFee", bl.getMainfestFee());
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveManifestFee(Integer id, java.math.BigDecimal mainfestFee, Integer userId) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return false;
        }
        
        bl.setMainfestFee(mainfestFee);
        // 与PHP逻辑一致：同时更新finance_check_details表（如果存在）
        // TODO: 实现finance_check_details表的更新逻辑
        return blMapper.updateById(bl) > 0;
    }
    
    @Override
    public Map<String, Object> getZgInfo(Integer id) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return null;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("id", bl.getId());
        result.put("blNo", bl.getBlNo());
        result.put("zgBlNo", bl.getZgBlNo());
        result.put("vndZgId", bl.getVndZgId());
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveZgInfo(Integer id, String zgBlNo, Integer vndZgId, Integer userId) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return false;
        }
        
        if (zgBlNo != null) {
            bl.setZgBlNo(zgBlNo);
        }
        if (vndZgId != null) {
            bl.setVndZgId(vndZgId);
        }
        
        return blMapper.updateById(bl) > 0;
    }
    
    @Override
    public Map<String, Object> getTxInfo(Integer id) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return null;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("id", bl.getId());
        result.put("blNo", bl.getBlNo());
        result.put("vndTxId", bl.getVndTxId());
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTxInfo(Integer id, Integer vndTxId, Integer userId) {
        LxBlList bl = blMapper.selectById(id);
        if (bl == null) {
            return false;
        }
        
        bl.setVndTxId(vndTxId);
        return blMapper.updateById(bl) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBlCosts(Integer id, List<LxBlCost> blCosts, Integer userId) {
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        for (LxBlCost blCost : blCosts) {
            if (blCost.getPrice() != null && blCost.getPrice().compareTo(java.math.BigDecimal.ZERO) > 0) {
                blCost.setBlId(id.longValue());
                blCost.setType(1); // 与PHP逻辑一致：type=1
                if (blCost.getId() != null && blCost.getId() > 0) {
                    // 更新
                    if (userId != null) {
                        blCost.setUpdateUid(userId);
                    }
                    blCost.setUpdateTime(currentTime);
                    blCostMapper.updateById(blCost);
                } else {
                    // 新增
                    if (userId != null) {
                        blCost.setAddUid(userId);
                    }
                    blCost.setAddTime(currentTime);
                    blCostMapper.insert(blCost);
                }
            }
        }
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBlCost(LxBlCost blCost, Integer userId) {
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        if (userId != null) {
            blCost.setUpdateUid(userId);
        }
        blCost.setUpdateTime(currentTime);
        return blCostMapper.updateById(blCost) > 0;
    }
}

